#include "../include/reader.h"

extern byte codes[0x10000];
extern byte data[0x10000];
extern byte stack[0x10000];
extern byte buffer[0x10000];

std::vector<pHeader> headers;

fHeader getHeader(const char *filename)
{
    std::ifstream inFile(filename, std::ios::binary);
    fHeader result;
    inFile.read((char *)&result, sizeof(fHeader));
    if (strcmp(result.magic, "sandbox") != 0)
    {
        std::cout << "fatal error:file type error.\n";
        exit(1);
    }
    else if (result.version != 0x201)
    {
        std::cout << "fatal error:file version error.\n";
        exit(1);
    }
    return result;
}
void getpHeader(const char *filename, fHeader fMessage)
{
    std::ifstream inFile(filename, std::ios::binary);
    inFile.seekg(fMessage.entry);
    for (int i = 0; i < fMessage.pcount; i++)
    {
        pHeader pMessage;
        inFile.read((char *)&pMessage, sizeof(pHeader));
        headers.push_back(pMessage);
    }
}
void loadImage(const char *filename)
{
    std::ifstream inFile(filename, std::ios::binary);
    for (auto &I : headers)
    {
        inFile.seekg(I.fbegin);
        switch (I.type)
        {
        case 0x00:
            inFile.read((char *)codes + I.pentry, I.psize);
            break;
        case 0x01:
            inFile.read((char *)data + I.pentry, I.psize);
            break;
        case 0x02:
            inFile.read((char *)stack + I.pentry, I.psize);
            break;
        case 0x03:
            inFile.read((char *)buffer + I.pentry, I.psize);
            break;
        }
    }
}